#!/bin/sh

if [ $# -lt 2 ]; then
    echo "Usage: $0 type name path system|user"
    exit 1
fi

provider_type=$1
group_name=$2
provider_path=$3
stype=$4
params=

if [ "$stype" == "system" ]; then
    params="--system";
fi

lib_dir=@prefix@/@DST_LIB@/statefs
scripts_dir=$lib_dir/scripts
scripts_install_dir=$RPM_BUILD_ROOT/${scripts_dir}

loader_dir=$scripts_dir/$provider_type
mkdir -p $RPM_BUILD_ROOT/$loader_dir
script_name=$loader_dir/on-$group_name
script_file=$RPM_BUILD_ROOT/$script_name
if ! [ -f $script_file ]; then
    echo "#!/bin/sh" > $script_file
    chmod +x $script_file
fi

order=03
if [ "$provider_type" == "loader" ]; then
    order=02
    action_script=$lib_dir/loader-action
    echo "$action_script \$1 $provider_path \${@:2}" \
        >> $script_file
else
    action_script=$lib_dir/provider-action
    echo "$action_script \$1 $provider_path $provider_type $params \${@:2}" \
        >> $script_file
fi

files=${group_name}.files
echo $script_name >> ${files}
echo $provider_path >> ${files}

# registration call goes to oneshot
reg_fname=@ONESHOT_DIR@/statefs-$order-register-$group_name
reg_file=$RPM_BUILD_ROOT/$reg_fname
if ! [ -f $reg_file ]; then
    mkdir -p $RPM_BUILD_ROOT/@ONESHOT_DIR@
    echo "#!/bin/sh" > $reg_file
    echo "$script_name register" >> $reg_file
    chmod +x $reg_file
fi

if ! [ -f ${files} ]; then
    echo $reg_fname > $files
elif ! grep $reg_fname ${files}; then
    echo $reg_fname >> $files
fi
